package 多线程.线程交替打印;
import java.util.concurrent.locks.LockSupport;

/**
 * 用LockSupport其实是最简单的
 * 让一个线程输出完了之后停止,然后让另外一个线程继续运行就完了
 */
public class 使用LockSupport {
    static char[] arr1 = "1234567".toCharArray();
    static char[] arr2 = "ABCDEFG".toCharArray();
    public static void main(String[] args) {
        t1.start();
        t2.start();

    }
    static Thread t1 = new Thread(){
        @Override
        public void run() {
            for (char c : arr1) {
                System.out.print(c);
                LockSupport.unpark(t2);//叫醒T2
                LockSupport.park();//T1阻塞
            }
        }
    };
    static Thread t2 = new Thread(){
        @Override
        public void run() {
            for (char c : arr2) {
                LockSupport.park();//t2阻塞
                System.out.print(c);
                LockSupport.unpark(t1);//叫醒t1
            }
        }
    };
}
class way2{
    /**
     * lambada表达式写法
     */
    static Thread t1 = null, t2 = null;
    public static void main(String[] args) throws Exception {
        char[] arr1 = "1234567".toCharArray();
        char[] arr2 = "ABCDEFG".toCharArray();
        t1 = new Thread(() -> {
            for (char c : arr1) {
                System.out.print(c);
                LockSupport.unpark(t2);//叫醒T2
                LockSupport.park();//T1阻塞
            }
        }, "t1");
        t2 = new Thread(() -> {
            for (char c : arr2) {
                LockSupport.park();//t2阻塞
                System.out.print(c);
                LockSupport.unpark(t1);//叫醒t1
            }
        }, "t2");
        t1.start();
        t2.start();
    }
}
